﻿using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;

public class SocketService : MonoBehaviour
{
	bool m_Active = false;
	Socket m_client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
	public void Listence()
    {
		IPAddress ip = IPAddress.Parse("127.0.0.1");
		IPEndPoint port = new IPEndPoint(ip, 0107);

		m_client.Bind(port);
		m_client.Listen(10);
		m_Active = true;
		//StartCoroutine(CorLis());
	}


	IEnumerator CorLis()
	{
		while (m_Active)
		{
			Socket so = m_client.Accept();
			string point = so.RemoteEndPoint.ToString();
			Debug.Log(point + "连接成功");
			//if(so != null )
			//{
			//	StartCoroutine(CorMsg(so));
			//}
			yield return null;
		}
	}

	IEnumerator CorMsg(Socket so)
	{
		bool active = true;
		while (active)
		{
			if (!so.Connected)
				break;
			byte[] buffer = new byte[1024 * 1024];
			int n = so.Receive(buffer);
			string words = Encoding.UTF8.GetString(buffer, 0, n);
			if(!string.IsNullOrEmpty(words))
				Debug.Log(words);
			yield return null;
		}
	}
    // Update is called once per frame
    void Update()
    {
		if (!m_Active)
			return;
	}
}
